package com.daisuxia.back.service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.daisuxia.back.dao.IBackUserDao;
import com.daisuxia.back.dao.IMmanLoanCollectionStatusChangeLogDao;
import com.daisuxia.back.utils.BackConstant;
import com.daisuxia.web.pojo.CreditLoanPay;
import com.daisuxia.web.pojo.MmanLoanCollectionOrder;
import com.daisuxia.web.pojo.MmanLoanCollectionPerson;
import com.daisuxia.web.pojo.MmanUserLoan;
import com.daisuxia.web.pojo.SysAlertMsg;
import com.daisuxia.web.util.DateUtil;

@Service
public class TaskJobMiddleService {
	
	protected Logger logger = LoggerFactory.getLogger(getClass());
	
	@Autowired
	private IMmanUserLoanService manUserLoanService;
	
	@Autowired
	private ICreditLoanPayService creditLoanPayService;
	
	@Autowired
	private IMmanLoanCollectionOrderService manLoanCollectionOrderService;
	
	@Autowired
	private IMmanLoanCollectionRecordService mmanLoanCollectionRecordService;
	
	@Autowired
	private IBackUserDao backUserDao;
	
	@Autowired
	private IMmanLoanCollectionStatusChangeLogDao mmanLoanCollectionStatusChangeLogDao;
	
	@Autowired
	private IAlertMsgService sysAlertMsgService; 
	
	
	
	/**
	 * 分配催收任务，更新催收相关操作(更新催收订单，添加流转日志，更新借款、还款逾期额天数状态等)
	 */
	public void autoDispatch() {
		logger.error("TaskJobMiddleService autoDispatch start");
		//初始化参数
		
		MmanUserLoan mmanUserLoan = new MmanUserLoan();
		mmanUserLoan.setLoanStatus(BackConstant.CREDITLOANAPPLY_OVERDUE);
		//mmanUserLoan.setCreateTime(new Date());
		List<MmanUserLoan> overdueList = manUserLoanService.findMmanUserLoanList2(mmanUserLoan);
		logger.error("overdueList size:"+overdueList.size());
		
		if (null!=overdueList && overdueList.size()>0) {
			for (MmanUserLoan mmanUserLoanOri : overdueList) {
				dispatchforLoanId(mmanUserLoanOri.getId()); 
			}
		}
		
		logger.error("TaskJobMiddleService autoDispatch end"); 
}
	
	
	public void dispatchforLoanId(String loanId){
		logger.error("dispatchforLoanId start,loanId:"+loanId);
		
		if(StringUtils.isBlank(loanId)){
			logger.error("dispatchforLoanId loanId is null");
			return;
		}
		
		MmanUserLoan mmanUserLoan = manUserLoanService.get(loanId);
		
		if(null == mmanUserLoan){
			logger.error("dispatchforLoanId mmanUserLoan is null,loanId:"+loanId);
			return;
		}
		
		if(!"4".equals(mmanUserLoan.getLoanStatus())){
			logger.error("dispatchforLoanId mmanUserLoan status is not equal 4,loanId:"+loanId);
			return;
		}
		
		dispatchForLoanId(mmanUserLoan);
		
		logger.error("dispatchforLoanId end,loanId:"+loanId);
		
	}
	
	
	
	
	/**
	 * 分配催收任务，更新催收相关操作(更新催收订单，添加流转日志，更新借款、还款逾期额天数状态等)
	 */
	public void dispatchForLoanId(MmanUserLoan mmanUserLoan) {
		if(null==mmanUserLoan) {
			logger.info("mmanUserLoan is null");
			return;
		}
		logger.error("TaskJobMiddleService dispatchForLoanId start");
		//初始化参数
		Date now = new Date();
		String sysName = "系统";
		String sysRemark = "系统派单";
		String sysPromoteRemark = "逾期升级，系统重新派单";
//		String ourCompanyId = "1";
		//和处理步骤对应的订单以及催收员列表
		List<MmanLoanCollectionOrder> mmanLoanCollectionOrderNoList = new ArrayList<MmanLoanCollectionOrder>();//订单
		List<MmanLoanCollectionPerson> mmanLoanCollectionPersonNoList = new ArrayList<MmanLoanCollectionPerson>();//催收组
		try {
			//更新借款
			CreditLoanPay creditLoanPay = creditLoanPayService.findByLoanId(mmanUserLoan.getId());
			if(null==creditLoanPay){
				logger.error("CreditLoanPay is null ,loanId:"+mmanUserLoan.getId());
				return;
			}
			
			if (creditLoanPay.getRealMoney() == null) {
				creditLoanPay.setRealMoney(new BigDecimal("0"));
			}
			BigDecimal loanMoney = mmanUserLoan.getLoanMoney();//借款金额
			if(BackConstant.CREDITLOANAPPLY_OVERDUE.equals(mmanUserLoan.getLoanStatus())){
				int pday = 0;
				try {
					pday=DateUtil.daysBetween(mmanUserLoan.getLoanEndTime(),new Date());
				} catch (ParseException e) {
					logger.error("parse failed",e);
				}
				BigDecimal pRate = new BigDecimal((Double.parseDouble(mmanUserLoan.getLoanPenaltyRate())/10000));//罚息率
				BigDecimal pmoney = (loanMoney.multiply(pRate).multiply(new BigDecimal(pday))).setScale(2, BigDecimal.ROUND_HALF_UP);//逾期金额（部分还款算全罚息)
				//如果逾期大于封顶逾期金额（封顶金额=原借款金额）则用最大值计算
				if(pmoney.compareTo(loanMoney)==1) {
					pmoney = loanMoney;
				}
				loanMoney = loanMoney.add(pmoney).setScale(2, BigDecimal.ROUND_HALF_UP);
				mmanUserLoan.setLoanPenalty(pmoney);//逾期滞纳金 DecimalFormatUtil.df2Points.format(pmoney.doubleValue())
				
				//外层循环处理时间随着数据量增长会越来越长，防止更新滞纳金（罚息）时覆盖更新已还款的数据
				MmanUserLoan mmanUserLoanForUpdate = new MmanUserLoan();
				mmanUserLoanForUpdate.setId(mmanUserLoan.getId());
				mmanUserLoanForUpdate.setLoanPenalty(mmanUserLoan.getLoanPenalty());
				manUserLoanService.updateMmanUserLoan(mmanUserLoanForUpdate);
				//更新还款表中滞纳金
				BigDecimal znj =  mmanUserLoan.getLoanPenalty().subtract(creditLoanPay.getRealgetInterest());
				CreditLoanPay np = new CreditLoanPay();
				np.setId(creditLoanPay.getId());
				np.setReceivableInterest(znj);
				np.setReceivableMoney(mmanUserLoan.getLoanMoney().add(mmanUserLoan.getLoanPenalty()));
				creditLoanPayService.updateCreditLoanPay(np);
				
				MmanLoanCollectionOrder mmanLoanCollectionOrder = new MmanLoanCollectionOrder();
				mmanLoanCollectionOrder.setLoanId(mmanUserLoan.getId());
				List<MmanLoanCollectionOrder> mmanLoanCollectionOrderList = manLoanCollectionOrderService.findList(mmanLoanCollectionOrder);
				//1.3.1 所有新订单，分组为S1
				if (null==mmanLoanCollectionOrderList || mmanLoanCollectionOrderList.isEmpty()) {
					
					logger.error("mmanLoancollectionOrder enter 13 ,mmanUserLoan id:"+mmanUserLoan.getId());
					
					MmanLoanCollectionOrder mmanLoanCollectionOrderNo = new MmanLoanCollectionOrder();
					mmanLoanCollectionOrderNo.setLoanId(mmanUserLoan.getId());
					mmanLoanCollectionOrderNo.setOrderId(mmanUserLoan.getLoanPyId());
					mmanLoanCollectionOrderNo.setUserId(mmanUserLoan.getUserId());
					mmanLoanCollectionOrderNo.setOverdueDays(pday);
					mmanLoanCollectionOrderNo.setPayId(creditLoanPay.getId());
					mmanLoanCollectionOrderNo.setDispatchName(sysName);
					mmanLoanCollectionOrderNo.setDispatchTime(now);
					mmanLoanCollectionOrderNo.setOperatorName(sysName);
					mmanLoanCollectionOrderNo.setRemark(sysRemark);
					mmanLoanCollectionOrderNo.setJxlStatus(BackConstant.XJX_JXL_STATUS_REFUSE);
					mmanLoanCollectionOrderNoList.add(mmanLoanCollectionOrderNo);
					
					Map<String,String> personMap = new HashMap<String,String>();
					personMap.put("dispatchTime",DateUtil.getDateFormat("yyyy-MM-dd"));
					personMap.put("groupLevel",BackConstant.XJX_OVERDUE_LEVEL_S1);
					personMap.put("userStatus", BackConstant.ON);

					mmanLoanCollectionPersonNoList = backUserDao.findUnCompleteCollectionOrderByAssignedCountListByMap(personMap);
					
					if (null==mmanLoanCollectionPersonNoList || mmanLoanCollectionPersonNoList.isEmpty()){
						logger.error("mmanLoancollectionOrder enter 13 no man,mmanUserLoan id:"+mmanUserLoan.getId());
						SysAlertMsg alertMsg = new SysAlertMsg();
						alertMsg.setTitle("分配催收任务失败");
						alertMsg.setContent("所有公司S1组查无可用催收人,请及时添加或启用该组催收员。");
						alertMsg.setDealStatus(BackConstant.OFF);
						alertMsg.setStatus(BackConstant.OFF);
						alertMsg.setType(SysAlertMsg.TYPE_COMMON);
						sysAlertMsgService.insert(alertMsg);
						logger.warn("所有公司S1组查无可用催收人...");
						return;
					} 
				} else {
					
					MmanLoanCollectionOrder mmanLoanCollectionOrderOri = mmanLoanCollectionOrderList.get(0);
					
					logger.error("mmanLoancollectionOrder enter 13 redispatch,mmanLoanCollectionOrder id:"+mmanLoanCollectionOrder.getId());
					
					if(BackConstant.XJX_COLLECTION_ORDER_DELETED.equals(mmanLoanCollectionOrderOri.getRenewStatus())){
						logger.error("mmanLoancollectionOrder renewStatus is deleted,do not dispatch,id:"+mmanLoanCollectionOrder.getId());
						return;
					}
					
					if(BackConstant.XJX_COLLECTION_ORDER_STATE_SUCCESS.equals(mmanLoanCollectionOrderOri.getStatus())){
						 logger.error("mmanLoancollectionOrder mmanLoanCollectionOrderOri status is success,do not dispatch,id:"+mmanLoanCollectionOrder.getId());
						 return;
					 }
					
					mmanLoanCollectionOrderOri.setOverdueDays(pday);
					
					//逾期天数 大于10的已存在未完成订单，分组升级为S2
					if (!BackConstant.XJX_OVERDUE_LEVEL_S2.equals(mmanLoanCollectionOrderOri.getCurrentOverdueLevel())&& pday >10 && pday <=30) {
						
						logger.error("mmanLoancollectionOrder enter 13 redispatch overdue>10,mmanLoanCollectionOrder id:"+mmanLoanCollectionOrder.getId());
						
						mmanLoanCollectionOrderOri.setDispatchName(sysName);
						mmanLoanCollectionOrderOri.setDispatchTime(now);
						mmanLoanCollectionOrderOri.setOperatorName(sysName);
						mmanLoanCollectionOrderOri.setRemark(sysPromoteRemark);
						mmanLoanCollectionOrderOri.setLastCollectionUserId(mmanLoanCollectionOrderOri.getCurrentCollectionUserId());//上一催收员

						//更新聚信立报告申请审核状态为初始状态，下一催收员要看需要重新申请
						mmanLoanCollectionOrderOri.setJxlStatus(BackConstant.XJX_JXL_STATUS_REFUSE);
						
						mmanLoanCollectionOrderNoList.add(mmanLoanCollectionOrderOri);
						
						Map<String,String> personMap = new HashMap<String,String>();
						personMap.put("dispatchTime",DateUtil.getDateFormat("yyyy-MM-dd"));
						personMap.put("groupLevel",BackConstant.XJX_OVERDUE_LEVEL_S2);
						personMap.put("userStatus", BackConstant.ON);
						
						mmanLoanCollectionPersonNoList = backUserDao.findUnCompleteCollectionOrderByAssignedCountListByMap(personMap);
						
						if (null==mmanLoanCollectionPersonNoList || mmanLoanCollectionPersonNoList.isEmpty()){
							logger.error("mmanLoancollectionOrder enter 10 < overdue <= 30 no man,mmanUserLoan id:"+mmanUserLoan.getId());
							SysAlertMsg alertMsg = new SysAlertMsg();
							alertMsg.setTitle("分配催收任务失败");
							alertMsg.setContent("所有公司S2组查无可用催收人,请及时添加或启用该组催收员。");
							alertMsg.setDealStatus(BackConstant.OFF);
							alertMsg.setStatus(BackConstant.OFF);
							alertMsg.setType(SysAlertMsg.TYPE_COMMON);
							sysAlertMsgService.insert(alertMsg);
							logger.warn("所有公司S2组查无可用催收人...");
							return;
						}
					}  else if(!BackConstant.XJX_OVERDUE_LEVEL_M1.equals(mmanLoanCollectionOrderOri.getCurrentOverdueLevel())&& pday >30 && pday <=60 ){
						logger.error("mmanLoancollectionOrder enter redispatch 30 <overdue <= 60 ,mmanLoanCollectionOrder id:"+mmanLoanCollectionOrder.getId());
						mmanLoanCollectionOrderOri.setDispatchName(sysName);
						mmanLoanCollectionOrderOri.setDispatchTime(now);
						mmanLoanCollectionOrderOri.setOperatorName(sysName);
						mmanLoanCollectionOrderOri.setRemark(sysPromoteRemark);
						mmanLoanCollectionOrderOri.setLastCollectionUserId(mmanLoanCollectionOrderOri.getCurrentCollectionUserId());//上一催收员

						//更新聚信立报告申请审核状态为初始状态，下一催收员要看需要重新申请
						mmanLoanCollectionOrderOri.setJxlStatus(BackConstant.XJX_JXL_STATUS_REFUSE);
						
						mmanLoanCollectionOrderNoList.add(mmanLoanCollectionOrderOri);
						
						Map<String,String> personMap = new HashMap<String,String>();
						personMap.put("dispatchTime",DateUtil.getDateFormat("yyyy-MM-dd"));
						personMap.put("groupLevel",BackConstant.XJX_OVERDUE_LEVEL_M1);
						personMap.put("userStatus", BackConstant.ON);
						
						mmanLoanCollectionPersonNoList = backUserDao.findUnCompleteCollectionOrderByAssignedCountListByMap(personMap);
						
						if (null==mmanLoanCollectionPersonNoList || mmanLoanCollectionPersonNoList.isEmpty()){
							logger.error("mmanLoancollectionOrder enter 30 <overdue <= 60 no man,mmanUserLoan id:"+mmanUserLoan.getId());
							SysAlertMsg alertMsg = new SysAlertMsg();
							alertMsg.setTitle("分配催收任务失败");
							alertMsg.setContent("所有公司M1组查无可用催收人,请及时添加或启用该组催收员。");
							alertMsg.setDealStatus(BackConstant.OFF);
							alertMsg.setStatus(BackConstant.OFF);
							alertMsg.setType(SysAlertMsg.TYPE_COMMON);
							sysAlertMsgService.insert(alertMsg);
							logger.warn("所有公司M1组查无可用催收人...");
							return;
						}
					}else if(!BackConstant.XJX_OVERDUE_LEVEL_M2.equals(mmanLoanCollectionOrderOri.getCurrentOverdueLevel())&& pday >60 && pday <=90 ){
						logger.error("mmanLoancollectionOrder enter redispatch 60 <overdue <= 90 ,mmanLoanCollectionOrder id:"+mmanLoanCollectionOrder.getId());
						mmanLoanCollectionOrderOri.setDispatchName(sysName);
						mmanLoanCollectionOrderOri.setDispatchTime(now);
						mmanLoanCollectionOrderOri.setOperatorName(sysName);
						mmanLoanCollectionOrderOri.setRemark(sysPromoteRemark);
						mmanLoanCollectionOrderOri.setLastCollectionUserId(mmanLoanCollectionOrderOri.getCurrentCollectionUserId());//上一催收员

						//更新聚信立报告申请审核状态为初始状态，下一催收员要看需要重新申请
						mmanLoanCollectionOrderOri.setJxlStatus(BackConstant.XJX_JXL_STATUS_REFUSE);
						
						mmanLoanCollectionOrderNoList.add(mmanLoanCollectionOrderOri);
						
						Map<String,String> personMap = new HashMap<String,String>();
						personMap.put("dispatchTime",DateUtil.getDateFormat("yyyy-MM-dd"));
						personMap.put("groupLevel",BackConstant.XJX_OVERDUE_LEVEL_M2);
						personMap.put("userStatus", BackConstant.ON);
						
						mmanLoanCollectionPersonNoList = backUserDao.findUnCompleteCollectionOrderByAssignedCountListByMap(personMap);
						
						if (null==mmanLoanCollectionPersonNoList || mmanLoanCollectionPersonNoList.isEmpty()){
							logger.error("mmanLoancollectionOrder enter 60 <overdue <= 90 no man,mmanUserLoan id:"+mmanUserLoan.getId());
							SysAlertMsg alertMsg = new SysAlertMsg();
							alertMsg.setTitle("分配催收任务失败");
							alertMsg.setContent("所有公司M2组查无可用催收人,请及时添加或启用该组催收员。");
							alertMsg.setDealStatus(BackConstant.OFF);
							alertMsg.setStatus(BackConstant.OFF);
							alertMsg.setType(SysAlertMsg.TYPE_COMMON);
							sysAlertMsgService.insert(alertMsg);
							logger.warn("所有公司M2组查无可用催收人...");
							return;
						}
					}else if(!BackConstant.XJX_OVERDUE_LEVEL_M3P.equals(mmanLoanCollectionOrderOri.getCurrentOverdueLevel())&& pday > 90 ){
						logger.error("mmanLoancollectionOrder enter redispatch overdue > 90 ,mmanLoanCollectionOrder id:"+mmanLoanCollectionOrder.getId());
						mmanLoanCollectionOrderOri.setDispatchName(sysName);
						mmanLoanCollectionOrderOri.setDispatchTime(now);
						mmanLoanCollectionOrderOri.setOperatorName(sysName);
						mmanLoanCollectionOrderOri.setRemark(sysPromoteRemark);
						mmanLoanCollectionOrderOri.setLastCollectionUserId(mmanLoanCollectionOrderOri.getCurrentCollectionUserId());//上一催收员

						//更新聚信立报告申请审核状态为初始状态，下一催收员要看需要重新申请
						mmanLoanCollectionOrderOri.setJxlStatus(BackConstant.XJX_JXL_STATUS_REFUSE);
						
						mmanLoanCollectionOrderNoList.add(mmanLoanCollectionOrderOri);
						
						
						Map<String,String> personMap = new HashMap<String,String>();
						personMap.put("dispatchTime",DateUtil.getDateFormat("yyyy-MM-dd"));
						personMap.put("groupLevel",BackConstant.XJX_OVERDUE_LEVEL_M3P);
						personMap.put("userStatus", BackConstant.ON);
						
						mmanLoanCollectionPersonNoList = backUserDao.findUnCompleteCollectionOrderByAssignedCountListByMap(personMap);
						
						if (null==mmanLoanCollectionPersonNoList || mmanLoanCollectionPersonNoList.isEmpty()){
							logger.error("mmanLoancollectionOrder enter overdue > 90 no man,mmanUserLoan id:"+mmanUserLoan.getId());
							SysAlertMsg alertMsg = new SysAlertMsg();
							alertMsg.setTitle("分配催收任务失败");
							alertMsg.setContent("所有公司M3+组查无可用催收人,请及时添加或启用该组催收员。");
							alertMsg.setDealStatus(BackConstant.OFF);
							alertMsg.setStatus(BackConstant.OFF);
							alertMsg.setType(SysAlertMsg.TYPE_COMMON);
							sysAlertMsgService.insert(alertMsg);
							logger.warn("所有公司M3+组查无可用催收人...");
							return;
						}
					}else {
						//原订单不在条件内的只需更新逾期天数
						manLoanCollectionOrderService.saveMmanLoanCollectionOrder(mmanLoanCollectionOrderOri);
						return;
					}
				}
				}
			} catch (Exception e) {
				logger.error("分配当前催收任务出错，借款ID：" + mmanUserLoan.getId(), e);
			}
		//2 将订单派到对应分组催收员
	    mmanLoanCollectionRecordService.assignCollectionOrderToRelatedGroup(mmanLoanCollectionOrderNoList, mmanLoanCollectionPersonNoList, now);
	}
	
	
	/**
	 * 根据派单订单id,查询是否有系统逾期升级至S2的转派日志
	 * @param loanCollectionOrderId
	 * @return
	 */
	public boolean checkLog(String loanCollectionOrderId){
		HashMap<String,String> paraMap = new HashMap<String,String>();
		paraMap.put("collectionOrderId", loanCollectionOrderId);
		int count = null==mmanLoanCollectionStatusChangeLogDao.findSystemUpToS2Log(paraMap)?0:mmanLoanCollectionStatusChangeLogDao.findSystemUpToS2Log(paraMap).intValue();
		
		if(count>0){
			return true;
		}
		
		return false;
		
	}
}

